#include "BlockQueue.hpp"
#include "Thread.hpp"
#include <memory>
#include <vector>
using namespace ThreadModule;


void MasterCore(BlockQueue<int>& bq)
{
    while(true)
    {
        int t = rand() % 100000;
        bq.EnQueue(t);
        std::cout << "master product a num : " << t << std::endl;
    }
}

void SlaverCore(BlockQueue<int>& bq)
{
    sleep(1);
    while(true)
    {
        int r;
        bq.Dequeue(r);
        std::cout << "slaver consume a num : " << r << std::endl;
        sleep(1);
    }
}


void Init(std::vector<Thread<BlockQueue<int>>>& threads, int num, BlockQueue<int>& bq, const std::string& nameprefix, func_t<BlockQueue<int>> func)
{
    for (int i = 0; i < num; i++)
    {
        std::string name = nameprefix + std::to_string(i + 1);
        threads.emplace_back(func, bq, name);
    }
}

void InitMaster(std::vector<Thread<BlockQueue<int>>>& threads, int num, BlockQueue<int>& bq)
{
    Init(threads, num, bq, "master", MasterCore);
}

void InitSlaver(std::vector<Thread<BlockQueue<int>>>& threads, int num, BlockQueue<int>& bq)
{
    Init(threads, num, bq, "slaver", SlaverCore);
}

void StartAll(std::vector<Thread<BlockQueue<int>>>& threads)
{
    for (auto& thread : threads)
        thread.Start();
}

void WaitAll(std::vector<Thread<BlockQueue<int>>>& threads)
{
    for (auto& thread : threads)
        thread.Join();
}

int main()
{
    srand(time(nullptr));
    BlockQueue<int>* bq = new BlockQueue<int>();
    std::vector<Thread<BlockQueue<int>>> threads;
    InitMaster(threads, 1, *bq);
    InitSlaver(threads, 2, *bq);
    StartAll(threads);
    WaitAll(threads);
    return 0;
}